/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author carolina
 */
class EmbeddedNewsMain {
    
    private int next = 0
    private def list = []
    private boolean analyzed = false

    def getNextNews = { login, pass  ->
         try {
             if (analyzed) {
                 if (next < list.size() - 1) {
                    next = next + 1
                 } else {
                    next = 0
                 }
             } else {
                list = conectaEmbeddedNews("http://tomcat.embedded.ufcg.edu.br/embeddednews/rest/getAllNews")
                analyzed = true
                next = 0
             }


           return list[next]
         } catch (Exception e) {
             println "Message: " + e.getMessage()
             return "Embedded Noticia!"
         }
    }

     private def conectaEmbeddedNews = { connect ->

        //def base = "http://tomcat.embedded.ufcg.edu.br/embeddednews/rest/getAllNews"
      /*  def url = new URL(connect)
        def connection = url.openConnection()

        if (connection.responseCode != 200) {
            println "Bad reponse"
            return ["Embedded News", "http://www.uol.com.br"]
        } else { */
            // def text = connection.content.text
            // parserXML(text)
            //println "connection conntent: " + connection.content.text
            //println "connection responseCode: " + connection.responseCode
            //println "connection respondeMessage: " + connection.responseMessage
            return this.getNews("src/embeddednews/getAllNews.xml")
     //  }
     //  return []
    }


    private def getNews = { text ->
        //def langs = new XmlParser().parseText("/EmbeddedUserController.groovy")
        //def langs = new XmlParser().parseText(text)
        def set = new XmlParser().parse(text)
        def list = []
        set.news.each {
            list.add(it.titlePT.text())
            list.add(it.link.text())
            //println it.titleENG.text()
        }
        return list
    }
}

